import { selectHotRank } from '@/services/api/api-tophub-hotrank';
import { Line } from '@ant-design/charts';
import { DrawerForm, ProCard, ProColumns, ProTable } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Spin, Statistic, Typography } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface DrawerHotRankDetailsProps {
  dom: React.ReactNode;
  hotIcon: JSX.Element;
  hotName: string;
  hotType: number;
  hotCity: number;
  hotId: string;
  onRefurbish: () => void;
}

const DrawerHotRankDetails: React.FC<DrawerHotRankDetailsProps> = ({
  dom,
  hotIcon,
  hotName,
  hotType,
  hotCity,
  hotId,
  onRefurbish,
}) => {
  const [time, setTime] = useState(() => Date.now());

  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [rankDetailData, setRankDetailData] = useState<TophubHotRankData.HotRankSelect>();

  const typeMap = {
    '1': '微博',
    '2': '抖音',
    '3': '百度',
    '4': '头条',
    '5': '知乎',
    '7': '快手',
  };

  const selectRankDetail = async () => {
    const res = await selectHotRank({ id: hotId });
    if (res.code === 0) {
      // var duration = moment.duration(moment(res.data.executeTime).diff(moment(res.data.insertTime)));
      var duration = res.data.onlineDuration

      let time;

      const seconds = Math.floor(duration / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);

      const remainingHours = hours % 24;
      const remainingMinutes = minutes % 60;

      if (days > 0) {
        time = `${days}天 ${remainingHours}小时 ${remainingMinutes}分钟`;
      } else if (hours > 0) {
        time = `${remainingHours}小时 ${remainingMinutes}分钟`;
      } else {
        time = `${remainingMinutes}分钟`;
      }
      res.data.onlineDuration = time
      setRankDetailData(res.data);
    }
  };

  const columns: ProColumns<TophubHotRankData.HotRankSelect>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          编号
        </span>
      ),
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          节点
        </span>
      ),
      dataIndex: 'typeName',
      align: 'center',
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          排名
        </span>
      ),
      dataIndex: 'topIndex',
      align: 'center',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          热度值
        </span>
      ),
      dataIndex: 'heatIndex',
      align: 'center',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          时间
        </span>
      ),
      dataIndex: 'createdTime',
      align: 'center',
    },
  ];

  const config = {
    data: rankDetailData?.tracks,
    xField: 'updateTime',
    yField: 'heatIndex',
    point: {
      shapeField: 'square',
      sizeField: 4,
    },
    interaction: {
      tooltip: {
        marker: false,
      },
    },
    style: {
      lineWidth: 2,
    },
    tooltip: {
      // 自定义 tooltip 的内容
      formatter: (datum) => {
        return {
          name: '热度值', // 自定义显示的名称
          value: datum.heatIndex, // 显示的值
        };
      },
    },
    slider: {
      x: { updateTime: (d) => d },
    },
  };
  return (
    <DrawerForm
      title={hotName}
      trigger={
        <a
          style={{
            textAlign: 'start',
          }}
        >
          {dom}
        </a>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 800,
      }}
      onOpenChange={(visible) => {
        if (visible) {
          selectRankDetail();
        }
      }}
      submitter={false}
    >

      <Spin spinning={!rankDetailData}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <Typography.Text style={{ fontSize: 20, fontWeight: 'bold' }}>
            {rankDetailData?.name}
          </Typography.Text>
          <div style={{ marginTop: 10 }}>
            <Typography.Text>来源： {typeMap[rankDetailData?.type]} </Typography.Text>
            <a
              href={rankDetailData?.url}
              target="_blank"
              style={{
                marginLeft: 10,
              }}
            >
              原文
            </a>
          </div>
        </div>

        <ProCard.Group direction={'row'}>
          <ProCard>
            <Statistic title="历史最高排名" value={rankDetailData?.maxTopIndex ? rankDetailData?.maxTopIndex : rankDetailData?.topIndex} />
          </ProCard>
          <ProCard.Divider type={'vertical'} />
          <ProCard>
            <Statistic
              title="最新热度"
              value={rankDetailData?.heatIndex == null ? '' : rankDetailData?.heatIndex}
            />
          </ProCard>
          <ProCard.Divider type={'vertical'} />
          <ProCard style={{ width: 300 }}>
            <Statistic title="在榜时长" value={rankDetailData?.onlineDuration} />
          </ProCard>
        </ProCard.Group>
        {Array.isArray(rankDetailData?.tracks) && rankDetailData?.tracks.length > 0 && (
          <ProCard title="热点趋势">
            <Line {...config} />
          </ProCard>
        )}
        <ProTable<TophubHotRankData.HotRankSelect>
          headerTitle="热点节点"
          columns={columns}
          actionRef={actionRef}
          dataSource={rankDetailData?.nodes}
          rowKey="key"
          // polling={2000}
          dateFormatter="id"
          defaultSize={'small'}
          search={false}
          options={false}
        />
      </Spin>
    </DrawerForm>
  );
};

export default DrawerHotRankDetails;
